<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import RoleApi from "@/api/modules/org/bean/role";
import managerServiceApi from "@/api/modules/org/bean/manger";
import RoleForm from "./component/role-form.vue";
import { redirectPath } from "@/utils/router-kit";
import { RoleEditUrl, RoleIndexUrl } from "@/views/org/mapping.json";
import RoleUnitUserList from "../role-unit-user/component/role-unit-user-list.vue";
import menuTree from "../app-menu/component/app-menu-tree.vue";
import RoleConflictList from "./component/role-conflict-list.vue";
const router = useRouter();
//表单子组件的ref
const RoleFormRef = ref<InstanceType<typeof RoleForm> | null>(null);
// 菜单树
const MenuTreeRef = ref();
// 菜单树（分配）
const MenuTreeDistributeRef = ref();

const RoleConflictListRef = ref();
const url = RoleIndexUrl;
//当前页面state
const RoleFormState = reactive({
  loading: false,
  roleId: router.currentRoute.value.params.id as string,
  getRoleFormData: () => RoleFormRef.value.getRoleFormData(),

  // 保存按钮点击事件
  onSaveButtonClick: () => {
    RoleFormState.loading = true;
    let master = RoleFormState.getRoleFormData();
    let detail: any[] = [];
    // 菜单权限选中节点数据处理
    MenuTreeRef.value.getCheckedNodes().forEach((item: { attributes: { menuCode: any } }) => {
      let element = {
        resourceId: item.attributes.menuCode,
        resourceOpt: 1,
        resourceType: "MENU",
        roleId: RoleFormState.roleId
      };
      detail.push(element);
    });
    // 菜单权限(分配)选中节点数据处理
    // 管理类型角色才有分配菜单的权限
    if (RoleFormState.distributeCardVisible) {
      MenuTreeDistributeRef.value.getCheckedNodes().forEach((item: { attributes: { menuCode: any } }) => {
        let element = {
          resourceId: item.attributes.menuCode,
          resourceOpt: 2,
          resourceType: "MENU",
          roleId: RoleFormState.roleId
        };
        detail.push(element);
      });
    }

    if (master.roleType != 1) {
      // 非管理角色
      master.adminRange = null;
    }

    RoleApi.saveMasterDetail(master, { insert: detail }, "update")
      .then(res => {
        RoleFormState.loading = false;
        ElNotification({ type: "success", message: "保存成功" });
        redirectPath(RoleEditUrl + RoleFormState.roleId);
      })
      .finally(() => {
        RoleFormState.loading = false;
      });
  },
  // 新增成功回调函数
  onAddFormSuccess: (formData: any) => {
    redirectPath(RoleEditUrl + formData.userId);
  },

  // 菜单权限（分配）是否显示
  distributeCardVisible: false,
  changeRoleType: (val: any) => {
    if (val == 1) {
      RoleFormState.distributeCardVisible = true;
    } else {
      RoleFormState.distributeCardVisible = false;
    }
  },

  ///// 树数据加载 start //////
  // 树节点数据
  treeData: [] as any[],
  // 已选择的树节点key 菜单权限
  setTreeKeys: [] as any[],
  // 已选择的树节点key 菜单权限（分配）
  setTreeDistributeKeys: [] as any[],
  // 加载树节点数据处理函数
  loadMenuTreeData: () => {
    managerServiceApi.getAdminResourceForRole("MENU", RoleFormState.roleId, RoleFormState.getRoleFormData().appId).then(res => {
      const treeNodeArr = res.data;
      treeNodeArr.forEach((item: any) => RoleFormState.handleTreeData(item, res.data));
      RoleFormState.treeData = treeNodeArr;
    });
  },
  // 处理树形数据，找已被勾选的
  handleTreeData: (parentMneu: any, resourceData: any[]) => {
    if (parentMneu.attributes.checked) {
      RoleFormState.setTreeKeys.push(parentMneu.id);
    }
    if (parentMneu.attributes.adminChecked) {
      RoleFormState.setTreeDistributeKeys.push(parentMneu.id);
    }
    resourceData.forEach(item => {
      item.menuName = item.text;
      item.menuId = item.id;
      RoleFormState.handleTreeData(item, item.children);
    });
  }
  ///// 树数据加载 end //////
});

onMounted(() => {
  RoleFormState.loadMenuTreeData();
  nextTick(() => {
    MenuTreeRef.value.setCheckedKeys(RoleFormState.setTreeKeys);
    MenuTreeDistributeRef.value.setCheckedKeys(RoleFormState.setTreeDistributeKeys);
  });
  if (RoleFormState.roleId) {
    RoleConflictListRef.value.loadTable();
  }
});
</script>

<template>
  <div v-loading="RoleFormState.loading" element-loading-text="正在更新...">
    <jxtech-basic-card title="角色与权限" class="jxtech-main-mb">
      <template #operationSpace>
        <jxtech-save-button @click="RoleFormState.onSaveButtonClick" v-auth="'org:qxgl:jsyqx:save'"> </jxtech-save-button>
        <JxtechBackButtonExt></JxtechBackButtonExt>
      </template>
      <role-form
        ref="RoleFormRef"
        :role-id="RoleFormState.roleId"
        @add-success="RoleFormState.onAddFormSuccess"
        @change-role-type="RoleFormState.changeRoleType"
      >
      </role-form>
      <role-unit-user-list :role-id="RoleFormState.roleId" v-auth="'org:qxgl:jsyqx:save'"> </role-unit-user-list>
    </jxtech-basic-card>
    <jxtech-basic-card title="菜单权限" class="jxtech-main-mb">
      <menu-tree
        ref="MenuTreeRef"
        :show-checkbox="true"
        :is-custom-tree-data="true"
        :custom-tree-data="RoleFormState.treeData"
      ></menu-tree>
    </jxtech-basic-card>
    <jxtech-basic-card title="菜单权限（分配）" v-show="RoleFormState.distributeCardVisible" class="jxtech-main-mb">
      <menu-tree
        ref="MenuTreeDistributeRef"
        :show-checkbox="true"
        :is-custom-tree-data="true"
        :custom-tree-data="RoleFormState.treeData"
      ></menu-tree>
    </jxtech-basic-card>

    <RoleConflictList v-if="RoleFormState.roleId" ref="RoleConflictListRef" :role-id="RoleFormState.roleId"></RoleConflictList>
  </div>
</template>
